<?php

namespace app\admin\service;

use AlibabaCloud\SDK\Dypnsapi\V20170525\Models\GetSmsAuthTokensResponseBody\data;
use app\admin\controller\GmApplyGame;
use app\admin\model\Apply;
use app\admin\model\BoxArticleTag;
use app\admin\model\BoxGame;
use app\admin\model\BoxGameCate;
use app\admin\model\BoxGameQnext;
use app\admin\model\game\BoxPcGameSource;
use app\admin\validate\BoxGameCateValidate;
use app\admin\validate\BoxGameValidate;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\facade\Log;

class BoxGameService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new BoxGame();
    }

    public function getList()
    {
        $param = request()->param();
        // 查询条件
        $map = [];
        if (isset($param['id']) && !empty($param['id'])) {
            $map[] = ['id', '=', $param['id']];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $map[] = ['status', '=', $param['status']];
        }
        if (isset($param['game_name']) && !empty($param['game_name'])) {
            $map[] = ['game_name', 'like', '%' . $param['game_name'] . '%'];
        }
        if (isset($param['began_time']) && !empty($param['began_time'])) {
            $map[] = ['create_time', '>=', strtotime($param['began_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $map[] = ['create_time', '<=', strtotime($param['end_time'])];
        }
        if (isset($param['open_type']) && $param['open_type'] != '') {
            $map[] = ['open_type', '=', $param['open_type']];
        }
        if (isset($param['device']) && $param['device'] != '') {
            $map[] = ['on_platform', 'like', '%'.$param['device'].'%'];
        }
        $list = $this->model->where($map)->paginate($param['limit'] ?? 20)->toArray();
        //获取游戏类别
        foreach ($list['data'] as &$value) {
            $this->model->cacheDelete($value['id']);
            $cate_id = explode(',', $value['cate_id']);
            $value['cate'] = BoxGameCate::where(['id' => $cate_id])->field('id,name')->select();
        }
        return message('操作成功', true, $list['data'] ?? []);
    }

    public function edit()
    {
        $param = request()->param();
        $validate = new BoxGameValidate();
        if (!$validate->check($param)) {
            return message($validate->getError(), false, null, 1);
        }
        $error = "";
        Db::startTrans();
        try {
            $rowId = $this->model->edit($param, $error);
            if (!$rowId) {
                Db::rollback();
                return message($error, false);
            }
            Db::commit();
            return message();
        } catch (\Exception $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }
    }


    public function callBackGmCheck($data)
    {
        $res['game_id'] = $data['is_gm'];
        $res['is_new'] = $data['is_new'];
        $res['is_fine'] = $data['is_elite'];
        $res['sign'] = (new GmApplyGameService())->createSdkSign($res);
        $url = Env::get('domain.gm_url').'/GameBoxApi/RsyncGameAttr';
        $result = json_decode(curl_post($url, $res), true);

        Log::error('result:'.json_encode($result));
        Log::error('url:'.$url);
        if ($result['code'] != 0) {
            throw new Exception($result['msg']);
        }
    }


    public function status()
    {
        $param = request()->param();
        return parent::status($param); // TODO: Change the autogenerated stub

    }

    /**
     * 获取所有游戏列表
     * @return array
     */
    public function gameCommonMenuList()
    {
        $gameList = $this->model->field(['id', 'game_name'])->order("id DESC")->select();

        return message("操作成功", true, $gameList);
    }

    /**
     * Desc : 发布官方贴获取游戏列表
     * User : you name
     * Date : 2023-12-28 13:56
     * @param $param
     * @return array
     */
    public function getGameList($param): array
    {
        $limit = $param['limit'] ?? 999999;
        if (isset($param['game_name']) &&!empty($param['game_name'])){
            $map[] = ['game_name', 'like', '%'. $param['game_name']. '%'];
        }
        $platform = $param['on_platform'] ?? '';
        $map[] = ['mark','=',1];
        $map[] = ['status','<>',2];
        $gameList = $this->model->field('id,game_name')->where($map);
        // 判断平台
        if(!is_array($platform)){
            $platform = explode(',', $platform);
        }

        if(is_array($platform) && count($platform) >= 1 && $platform[0] != ''){
            $gameList = $gameList->where(function ($query) use ($platform) {
                foreach ($platform as $key => $value) {
                    $query->whereOr(Db::raw("FIND_IN_SET('{$value}',on_platform)"));
                }
            });
        }
        $gameList = $gameList->order("id DESC")->paginate($limit)->toArray();
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $gameList['data'] ?? [],
            "count" => $gameList['total'] ?? 0,
        );
    }

    /**
     * Desc : 获取帖子标签列表
     * User : you name
     * Date : 2024-02-01 15:32
     * @return array
     */
    public function getTagList(): array
    {
        return message("操作成功", true, BoxArticleTag::field('id,name')->select());
    }

    /**
     * Desc : getPcGameDownloadUrl
     * User : Steven
     * Date : 2024-06-28 17:43
     * @return array
     */
    public function getPcGameDownloadUrl(): array
    {
        $param = request()->param();
        $packageId= $param['package_id'] ?? 0;
        if (!$packageId) {
            return message("PC游戏包参数不存在!", false);
        }
        $applyModel = new Apply();
        $promote_id = env('default_promote_id.promote_id');
        $game = $applyModel->field('pc_down_resources')->where(['package_id' => $packageId, 'promote_id' => $promote_id])->find();
        if (!$game) {
            return message("PC游戏下载地址不存在,请配置PC游戏下载地址!", false);
        }
        return message("操作成功",true, $game);
    }
}
